<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改密码</title>
    <style>
        .container {
            width: 500px;
            margin: 50px auto;
            background-color: #f9f9f9;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .form-group {
            margin: 15px 0;
        }
        label {
            display: inline-block;
            width: 120px;
            font-weight: bold;
        }
        input {
            padding: 8px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .btn {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn-cancel {
            background: #6c757d;
        }
        .btn-cancel:hover {
            background: #545b62;
        }
        .error {
            color: red;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }
        .form-message {
            text-align: center;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
            display: none;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
        }
        .password-strength {
            margin-top: 5px;
            font-size: 14px;
        }
        .strength-weak {
            color: #dc3545;
        }
        .strength-medium {
            color: #ffc107;
        }
        .strength-strong {
            color: #28a745;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 style="text-align: center;">修改密码</h1>
    
    <!-- 服务端错误信息 -->
    <div th:if="${errorMsg != null}" class="error-message" style="text-align: center; padding: 10px; margin-bottom: 20px; border-radius: 4px; background-color: #f8d7da; color: #721c24;"><span th:text="${errorMsg}"></span></div>
    
    <!-- 提示信息 -->
    <div id="formMessage" class="form-message"></div>
    
    <!-- 密码修改表单 -->
    <form id="resetPasswordForm">
        <div class="form-group">
            <label>原密码：</label>
            <input type="password" id="oldPassword" name="oldPassword" placeholder="请输入原密码">
            <div id="oldPasswordError" class="error"></div>
        </div>
        
        <div class="form-group">
            <label>新密码：</label>
            <input type="password" id="newPassword" name="newPassword" placeholder="请输入新密码（至少6位）">
            <div id="newPasswordError" class="error"></div>
            <div id="passwordStrength" class="password-strength"></div>
        </div>
        
        <div class="form-group">
            <label>确认新密码：</label>
            <input type="password" id="confirmPassword" name="confirmPassword" placeholder="请再次输入新密码">
            <div id="confirmPasswordError" class="error"></div>
        </div>
        
        <div class="form-group" style="text-align: center;">
            <button type="submit" class="btn">确认修改</button>
            <button type="button" class="btn btn-cancel" onclick="window.history.back()">取消</button>
        </div>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('resetPasswordForm');
        const oldPasswordInput = document.getElementById('oldPassword');
        const newPasswordInput = document.getElementById('newPassword');
        const confirmPasswordInput = document.getElementById('confirmPassword');
        const formMessage = document.getElementById('formMessage');
        const passwordStrength = document.getElementById('passwordStrength');

        // 密码强度检测
        newPasswordInput.addEventListener('input', function() {
            const password = this.value;
            if (password) {
                const strength = checkPasswordStrength(password);
                let strengthText = '';
                let strengthClass = '';
                
                switch(strength) {
                    case 0:
                    case 1:
                        strengthText = '密码强度：弱';
                        strengthClass = 'strength-weak';
                        break;
                    case 2:
                        strengthText = '密码强度：中';
                        strengthClass = 'strength-medium';
                        break;
                    case 3:
                        strengthText = '密码强度：强';
                        strengthClass = 'strength-strong';
                        break;
                }
                
                passwordStrength.textContent = strengthText;
                passwordStrength.className = 'password-strength ' + strengthClass;
            } else {
                passwordStrength.textContent = '';
                passwordStrength.className = 'password-strength';
            }
        });

        // 确认密码与新密码一致性检查
        confirmPasswordInput.addEventListener('input', function() {
            const confirmPassword = this.value;
            const newPassword = newPasswordInput.value;
            const confirmPasswordError = document.getElementById('confirmPasswordError');
            
            if (confirmPassword && confirmPassword !== newPassword) {
                confirmPasswordError.textContent = '两次输入的新密码不一致';
                confirmPasswordError.style.display = 'block';
            } else {
                confirmPasswordError.style.display = 'none';
            }
        });

        // 表单提交处理
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 清除之前的错误信息
            clearErrors();
            formMessage.style.display = 'none';
            
            // 获取表单数据
            const oldPassword = oldPasswordInput.value.trim();
            const newPassword = newPasswordInput.value.trim();
            const confirmPassword = confirmPasswordInput.value.trim();
            
            // 前端验证
            let isValid = true;
            
            if (!oldPassword) {
                showError('oldPasswordError', '请输入原密码');
                isValid = false;
            }
            
            if (!newPassword) {
                showError('newPasswordError', '请输入新密码');
                isValid = false;
            } else if (newPassword.length < 6) {
                showError('newPasswordError', '新密码长度不能小于6位');
                isValid = false;
            }
            
            if (!confirmPassword) {
                showError('confirmPasswordError', '请确认新密码');
                isValid = false;
            } else if (confirmPassword !== newPassword) {
                showError('confirmPasswordError', '两次输入的新密码不一致');
                isValid = false;
            }
            
            // 如果前端验证通过，则发送请求
            if (isValid) {
                // 创建表单数据
            const params = new URLSearchParams();
            params.append('oldPassword', oldPassword);
            params.append('newPassword', newPassword);
            params.append('confirmPassword', confirmPassword);
            
            // 显示加载状态
            const submitButton = form.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.disabled = true;
            submitButton.textContent = '处理中...';
            
            // 发送请求
            fetch('/echo-network/reset-password', {
                method: 'POST',
                body: params,
                credentials: 'include' // 确保请求携带cookie信息
            })
                .then(response => response.json())
                .then(data => {
                    submitButton.disabled = false;
                    submitButton.textContent = originalText;
                    
                    if (data.success) {
                        // 显示成功消息
                        showFormMessage('success-message', data.message);
                        
                        // 3秒后跳转到登录页
                        setTimeout(function() {
                            window.location.href = '/echo-network/login';
                        }, 3000);
                    } else {
                        // 显示错误消息
                        showFormMessage('error-message', data.message);
                    }
                })
                .catch(error => {
                    submitButton.disabled = false;
                    submitButton.textContent = originalText;
                    // 添加更详细的错误信息
                    let errorMessage = '网络错误，请稍后重试';
                    if (error instanceof TypeError) {
                        errorMessage = '网络连接错误：服务器可能不可达';
                    } else if (error instanceof SyntaxError) {
                        errorMessage = '数据解析错误：服务器返回的格式不正确';
                    } else if (error.message) {
                        errorMessage = '错误：' + error.message;
                    }
                    showFormMessage('error-message', errorMessage);
                    console.error('详细错误信息:', error);
                });
            }
        });

        // 辅助函数
        function clearErrors() {
            const errorElements = document.querySelectorAll('.error');
            errorElements.forEach(element => {
                element.style.display = 'none';
                element.textContent = '';
            });
        }
        
        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.style.display = 'block';
        }
        
        function showFormMessage(type, message) {
            formMessage.textContent = message;
            formMessage.className = 'form-message ' + type;
            formMessage.style.display = 'block';
        }
        
        function checkPasswordStrength(password) {
            let strength = 0;
            
            // 长度检查
            if (password.length >= 8) strength++;
            
            // 包含数字
            if (/\d/.test(password)) strength++;
            
            // 包含字母（大小写）
            if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
            
            // 包含特殊字符
            if (/[^A-Za-z0-9]/.test(password)) strength++;
            
            return Math.min(strength, 3); // 限制在0-3之间
        }
    });
</script>
</body>
</html>